package com.repast.utils;

import com.repast.vo.PayMoneyInfo;
import com.thoughtworks.xstream.XStream;
import com.weixinpay.common.Configure;
import com.weixinpay.common.HttpRequest;
import com.weixinpay.common.RandomStringGenerator;
import com.weixinpay.common.Signature;
import com.weixinpay.model.OrderInfo;
import com.weixinpay.model.OrderReturnInfo;
import com.weixinpay.model.SignInfo;

public class PackagePayInfo {

	public static PayMoneyInfo packageMessage(String ordersNum, String openid, Double ordersTotal) throws Exception {
		// 先支付,支付成功后数据插入订单
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setAppid(Configure.getAppID());// 小程序的appID
		orderInfo.setMch_id(Configure.getMch_id());// 小程序的商户支付账号
		orderInfo.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));// 随机生成一个32位的字符串,商户需要的参数
		// 商品描述
		orderInfo.setBody(new StringBuilder().append("订单").append(ordersNum).append("购买商品共")
				.append(ordersTotal).append("元").toString());
		orderInfo.setOut_trade_no(RandomStringGenerator.getRandomStringByLength(32));// 商户订单号
		// 订单的总额
		// int total_fee =new Double(ordersVo.getOrdersTotal()*100).intValue();
		// 这里只支付1分做测试使用
		orderInfo.setTotal_fee(1);
		orderInfo.setSpbill_create_ip("123.57.218.54");// 终端ip,用户端实际ip
		orderInfo.setNotify_url("https://www.bmzebra.com/weixinpay/PayResult");// 支付的通知地址,也是回调信息的地址
		orderInfo.setTrade_type("JSAPI");
		orderInfo.setOpenid(openid);
		orderInfo.setSign_type("MD5");// 签名类型
		String sign = Signature.getSign(orderInfo);// 把所有的数据封装到签名中
		orderInfo.setSign(sign);

		String result = HttpRequest.sendPost("https://api.mch.weixin.qq.com/pay/unifiedorder", orderInfo);
		System.out.println("返回的result:" + result);
		XStream xStream = new XStream();
		xStream.alias("xml", OrderReturnInfo.class);
		OrderReturnInfo returnInfo = (OrderReturnInfo) xStream.fromXML(result);

		String prepayId = returnInfo.getPrepay_id();// prepayId

		SignInfo signInfo = new SignInfo();
		signInfo.setAppId(Configure.getAppID());
		long time = System.currentTimeMillis() / 1000;
		signInfo.setTimeStamp(String.valueOf(time));
		signInfo.setNonceStr(RandomStringGenerator.getRandomStringByLength(32));
		signInfo.setPrepayId("prepay_id=" + prepayId);
		signInfo.setSignType("MD5");

		PayMoneyInfo info = new PayMoneyInfo();
		String paySign = Signature.getSign(signInfo);
		info.setSignInfo(signInfo);
		info.setOrdersTotal(ordersTotal);
		info.setPaySign(paySign);
		info.setOrdersNum(ordersNum);
		
		return info;
	}
}
